﻿using ciji.Application.Dto;
using ciji.Core;
using Furion;
using Microsoft.Data.SqlClient;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace ciji.Application.Data
{
    /// <summary>
    /// 基础数据
    /// </summary>
    [ApiDescriptionSettings("基础数据", Order = 700, Description = "基础数据接口")]
    public class BasicService : IDynamicApiController
    {
        private static string DiskPath = App.Configuration["FileConfig:DiskPath"];
        private static string OutUrl = App.Configuration["FileConfig:OutUrl"];
        private static string bucketName = App.Configuration["FileConfig:bucketName"];
        private SqlSugarRepository<cts_Employee> _employeeRep;
        private SqlSugarRepository<cts_Area> _areaRep;
        private SqlSugarRepository<cts_CompanySign> _companySignRep;
        private SqlSugarRepository<cts_SignImg> _signImgRep;
        private SqlSugarRepository<cts_Contacts> _contactsRep;

        public BasicService(SqlSugarRepository<cts_Employee> employeeRep
            , SqlSugarRepository<cts_Area> areaRep
            , SqlSugarRepository<cts_CompanySign> companySignRep
            , SqlSugarRepository<cts_SignImg> signImgRep
            , SqlSugarRepository<cts_Contacts> contactsRep)
        {
            _employeeRep = employeeRep;
            _areaRep = areaRep;
            _companySignRep = companySignRep;
            _signImgRep = signImgRep;
            _contactsRep = contactsRep;
        }

        #region 员工管理
        /// <summary>
        /// 保存员工信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [SecurityDefine("admin")]
        [LoggingMonitor]
        public bool SaveEmployee(cts_Employee input)
        {

            var existCount = _employeeRep.AsQueryable().Where(m => m.Account == input.Account && m.Id != input.Id).Count();
            if (existCount > 0)
            {
                throw Oops.Bah("该登录账号已存在");
            }
            if (input.Id == 0)
            {
                input.Gid = Guid.NewGuid().ToString();
                input.Password = EncryptLibrary.MD5Encrypt(AppStr.DeafultPwd, EncryptLibrary.getkey());
                return _employeeRep.Insert(input);
            }
            else
            {
                return _employeeRep.Update(input);
            }
        }
        /// <summary>
        /// 修改员工头像
        /// </summary>
        /// <param name="avator"></param>
        /// <returns></returns>
        [LoggingMonitor]
        public int UpdateAvator([FromQuery] string avator)
        {
            return _employeeRep.AsUpdateable().SetColumns(m => m.EmployeeAvator == avator).Where(m => m.Gid == UserHelper.GetUserId()).ExecuteCommand(); ;
        }
        /// <summary>
        /// 查询员工信息
        /// type.0所有，1只查评估员
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public List<cts_Employee> SearchEmployee(EmployeSearchDto input)
        {
            return _employeeRep.AsQueryable().IgnoreColumns(m => m.Password)
                .Where(m=>m.Type==input.type)
                .WhereIF(input.type == 1, m => m.Auth == 1).ToList();
        }
        /// <summary>
        /// 查询区域代表信息
        /// </summary>
        /// <returns></returns>
        public List<cts_Employee> SearchAreaEmployee()
        {
            return _employeeRep.AsQueryable()
                .LeftJoin<cts_Area>((a, b) => a.AreaId == b.Gid)
                .Select((a, b) => new cts_Employee
                {
                    Id = a.Id.SelectAll(),
                    AreaInfo = b,
                })
                .IgnoreColumns(a => a.Password).Where(a => a.Auth == 4 && a.Type == 1)
                .ToList();
        }


        /// <summary>
        /// 删除员工信息
        /// </summary>
        /// <param name="gid"></param>
        /// <returns></returns>
        [SecurityDefine("admin")]
        [LoggingMonitor]
        public int DeleteEmployee(string gid)
        {
            return _employeeRep.AsUpdateable().SetColumns(m => m.sys_IsDelete == 1).Where(m => m.Gid == gid).ExecuteCommand();
        }


        /// <summary>
        /// 重置员工密码
        /// </summary>
        /// <param name="gid"></param>
        /// <returns></returns>
        [SecurityDefine("admin")]
        [LoggingMonitor]
        public int ResetEmployeePwd(string gid)
        {
            var pwd = EncryptLibrary.MD5Encrypt(AppStr.DeafultPwd, EncryptLibrary.getkey());
            return _employeeRep.AsUpdateable().SetColumns(m => m.Password == pwd).Where(m => m.Gid == gid).ExecuteCommand();
        }
        #endregion

        #region 区域管理
        /// <summary>
        /// 查询区域信息
        /// </summary>
        /// <returns></returns>
        public List<cts_Area> SearchArea()
        {
            return _areaRep.GetList();
        }
        /// <summary>
        /// 保存区域
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [SecurityDefine("admin")]
        [LoggingMonitor]
        public bool SaveArea(cts_Area input)
        {
            if (input.Id > 0)
            {
                return _areaRep.Update(input);
            }
            else
            {
                input.Gid = Guid.NewGuid().ToString();
                return _areaRep.Insert(input);
            }
        }
        /// <summary>
        /// 删除区域
        /// </summary>
        /// <param name="gid"></param>
        /// <returns></returns>
        [SecurityDefine("admin")]
        [LoggingMonitor]
        public void DeleteArea(string gid)
        {
             _areaRep.Delete(m=>m.Gid==gid);
        }
        #endregion

        #region 公司签章
        /// <summary>
        /// 获取公司公章
        /// </summary>
        /// <returns></returns>
        public List<cts_CompanySign> GetCompanySign()
        {

            return _companySignRep.GetList();
        }
        /// <summary>
        /// 保存公司公章
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [SecurityDefine("admin")]
        [LoggingMonitor]
        public bool SaveCompanySign(cts_CompanySign input)
        {
            if (input.Id > 0)
            {
                return _companySignRep.Update(input);
            }
            else
            {
                input.Gid = Guid.NewGuid().ToString();
                return _companySignRep.Insert(input);
            }

        }

        /// <summary>
        /// 删除公司公章信息
        /// </summary>
        /// <param name="gid"></param>
        /// <returns></returns>
        [SecurityDefine("admin")]
        [LoggingMonitor]
        public void DeleteCompanySign(string gid)
        {
             _companySignRep.Delete(m => m.Gid == gid) ;
        }

        #endregion

        #region 签名图片

        /// <summary>
        /// 获取签名图片
        /// </summary>
        /// <returns></returns>
        public List<cts_SignImg> SearchSignImg()
        {

            return _signImgRep.GetList();
        }
        /// <summary>
        /// 保存签名图片
        /// </summary>
        /// <param name="file"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        [SecurityDefine("admin")]
        [LoggingMonitor]
        public async Task<bool> AddSignImg(IFormFile file, [FromForm] string name)
        {
            var now = DateTimeOffset.Now;
            var dicPath = $@"{bucketName}/imgyanglao/{now.Year}/{now.Month}/{name}/{Guid.NewGuid().ToString()}";

            var savePath = Path.Combine(DiskPath, dicPath);
            var fileName = file.FileName;

            var linkPath = Path.Combine(dicPath, fileName);
            var extension = Path.GetExtension(fileName);

            if (!Directory.Exists(savePath))
            {
                Directory.CreateDirectory(savePath);
            }

            var filePath = Path.Combine(savePath, fileName);

            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }

            cts_SignImg cs = new cts_SignImg();
            cs.ImgUrl = OutUrl + linkPath;
            cs.Gid = Guid.NewGuid().ToString();
            return _signImgRep.Insert(cs);
        }

        /// <summary>
        /// 删除签名图片
        /// </summary>
        /// <param name="gid"></param>
        /// <returns></returns>
        [SecurityDefine("admin")]
        [LoggingMonitor]
        public void DeleteSignImg(string gid)
        {
            _signImgRep.Delete(m => m.Gid == gid) ;
        }



        #endregion


        #region 通讯录

        /// <summary>
        /// 通讯录查询
        /// </summary>     
        /// <returns></returns> 
        public SqlSugarPagedXList<cts_Contacts> SearchContacts(SearchInputDto input)
        {


            return _contactsRep.AsQueryable().WhereIF(!string.IsNullOrEmpty(input.areaid), m => m.AreaId == input.areaid)
                 .WhereIF(!string.IsNullOrEmpty(input.str), m => m.Name.Contains(input.str) || m.Phone.Contains(input.str) || m.Job.Contains(input.str) || m.Organization.Contains(input.str))
                 .ToPagedList(input.page, input.size);
        }
        /// <summary>
        /// 通讯录保存
        /// </summary>     
        /// <returns></returns> 
        public bool SaveContacts(cts_Contacts input)
        {

            if (input.Id > 0)
            {
                return _contactsRep.Update(input);
            }
            else
            {
                input.Gid = Guid.NewGuid().ToString();
                return _contactsRep.Insert(input);
            }
        }
        /// <summary>
        /// 删除通讯录
        /// </summary>     
        /// <returns></returns> 
        public int DeleteContacts(string gid)
        {
            return _contactsRep.AsUpdateable().SetColumns(m => m.sys_IsDelete == 1).Where(m => m.Gid == gid).ExecuteCommand();
        }
        #endregion

    }
}